package com.stn.zjx.givingtreasure.activity.dynamic;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.irozon.sneaker.Sneaker;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.activity.common.DropImgsShowActivity;
import com.stn.zjx.givingtreasure.adapter.DynamicGuestAdapter;
import com.stn.zjx.givingtreasure.adapter.DynamicRecommandListAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.DynamicDetailDomain;
import com.stn.zjx.givingtreasure.domain.DynamicGuestDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicLikeNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicNetImpl;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@SuppressWarnings("all")
public class DynamicDetailGuestListActivity extends BaseActivity {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.like_iv)
    ImageView likeIv;
    @BindView(R.id.like_tv)
    TextView likeTv;
    @BindView(R.id.like_bt)
    LinearLayout likeBt;
    @BindView(R.id.guest_iv)
    ImageView guestIv;
    @BindView(R.id.guest_bt)
    LinearLayout guestBt;
    @BindView(R.id.open_guest)
    LinearLayout openGuest;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.hot_title)
    TextView hotTitle;
    @BindView(R.id.hot_rv)
    RecyclerView hotRv;
    @BindView(R.id.up_layout)
    LinearLayout upLayout;
    @BindView(R.id.new_update_title)
    TextView newUpdateTitle;
    @BindView(R.id.new_update_rv)
    RecyclerView newUpdateRv;
    @BindView(R.id.no_data)
    LinearLayout noData;
    @BindView(R.id.bottom_loading_tv)
    TextView bottomLoadingTv;
    @BindView(R.id.bottom_loading)
    RelativeLayout bottomLoading;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.twinkling_refresh)
    TwinklingRefreshLayout twinklingRefresh;
    @BindView(R.id.rootView)
    LinearLayout rootView;
    private int id=0;
    private LinearLayoutManager new_updaet_rc;
    private DynamicGuestAdapter newUpdateAdpater;
    private LinearLayoutManager hot_rc;
    private DynamicGuestAdapter hotAdpater;
    public int pageNow = 1;
    public int pageSize = 10;
    public boolean isMoreLoading = false;
    public boolean isOpenKeywowrd = false;
    private BadgeView badgeView;
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }
    //登录刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFragmentLoginRefresh(RefreshEvent event) {
        if (event.flag == RefreshEvent.LOGIN_REFRESH) {
            initInfo();
            initData();
        } else if (event.flag == RefreshEvent.REFRESH) {
            initData();
        }
    }


    @Override
    public void initComponent() {
        id = getIntent().getIntExtra("id", 0);
        actionTitle.setText(getString(R.string.guest_detail));
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (scrollY == (nestedScrollView.getChildAt(0).getMeasuredHeight() - nestedScrollView.getMeasuredHeight())) {

                    if (!isMoreLoading && newUpdateAdpater.dataBeanList.size() >= pageNow * pageSize) {
                        User onlineUser = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
                        String token = "";
                        if (onlineUser == null) {
                            token = "";
                        } else {
                            token = onlineUser.getToken();
                        }
                        query_new_update_dynamic_guest_append(token, id);
                    }
                }

            }
        });
        badgeView = BadgeFactory.create(this)
                .setTextColor(getResources().getColor(R.color.white))
                .setWidthAndHeight(15, 15)
                .setBadgeBackground(getResources().getColor(R.color.red))
                .setTextSize(8)
                .setMargin(10, 0, 0, 5)
                .setBadgeGravity(Gravity.RIGHT | Gravity.TOP)
                .setBadgeCount("0")
                .setShape(BadgeView.SHAPE_CIRCLE)
                .bind(guestIv);


        new_updaet_rc = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        newUpdateRv.setLayoutManager(new_updaet_rc);
        newUpdateAdpater = new DynamicGuestAdapter(this);
        newUpdateRv.setAdapter(newUpdateAdpater);

        hot_rc = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        hotRv.setLayoutManager(hot_rc);
        hotAdpater = new DynamicGuestAdapter(this);
        hotRv.setAdapter(hotAdpater);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_guest_list);
        ButterKnife.bind(this);
        initComponent();
//        initGuestDialog();
        initInfo();
        initData();

    }
    public void initInfo() {
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        String token = "";
        if (onlineUser == null) {
            token = "";
        } else {
            token = onlineUser.getToken();
        }
        UserDynamicNetImpl
                .query_dynamic_detail(token, id, id + "query_dynamic_detail_" + token, new StringCallback() {
                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful() && !isFinishing()) {
                            initDynamicDetailResult(response.body());
                        }
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            initDynamicDetailResult(response.body());
                        }

                    }
                });

    }

    @OnClick({R.id.back_bt, R.id.open_guest, R.id.guest_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.back_bt:
                finish();
                break;
            case R.id.open_guest:
                User onlineUser = UserService
                        .getInstance(this)
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(this, UserLoginActivity.class);
                    return;
                }
                initGuestDialog();
                break;
            case R.id.guest_bt:
                nestedScrollView.smoothScrollTo(0, upLayout.getMeasuredHeight());
                break;
        }
    }

    public void initDynamicDetailResult(String body) {
        DynamicDetailDomain domain = new Gson().fromJson(body, DynamicDetailDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:


                if (domain.getData().getDetailData().getGuestCount() >= 99) {
                    badgeView.setBadgeCount("99+");
                } else {
                    badgeView.setBadgeCount("" + domain.getData().getDetailData().getGuestCount());
                }
                switch (domain.getData().getDetailData().getIsLike()) {
                    case 0:
                        likeIv.setImageResource(R.mipmap.no_like);
                        likeTv.setText(getString(R.string.like));
                        break;
                    case 1:
                        likeIv.setImageResource(R.mipmap.yes_like);
                        likeTv.setText(getString(R.string.alreay_like));
                        break;
                }

                likeBt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        User onlineUser = UserService
                                .getInstance(getApplicationContext())
                                .getOnlineLoginUser();
                        if (onlineUser == null) {
                            RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                            return;
                        }
                        switch (domain.getData().getDetailData().getIsLike()) {
                            case 0:
                                likeIv.setImageResource(R.mipmap.yes_like);
                                domain.getData().getDetailData().setIsLike(1);
                                set_dynamic_like(onlineUser.getToken(), domain.getData().getDetailData().getUserDynamicId());
                                likeTv.setText(getString(R.string.alreay_like));
                                break;
                            default:
                                likeIv.setImageResource(R.mipmap.no_like);
                                domain.getData().getDetailData().setIsLike(0);
                                set_dynamic_no_like(onlineUser.getToken(), domain.getData().getDetailData().getUserDynamicId());
                                likeTv.setText(getString(R.string.like));
                                break;
                        }
                    }
                });

                break;
        }
    }
    //设置喜欢
    public void set_dynamic_like(String token, Integer userDynamicId) {
        UserDynamicLikeNetImpl
                .set_like_dynamic(token, userDynamicId, token + "_set_like_dynamic_" + userDynamicId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //设置不喜欢
    public void set_dynamic_no_like(String token, Integer userDynamicId) {
        UserDynamicLikeNetImpl
                .set_no_like_dynamic(token, userDynamicId, token + "_set_dynamic_no_like_" + userDynamicId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }


    //查询最新，热门动态评论
    public void query_new_update_dynamic_guest(String token, Integer userDynamicId
    ) {
        pageNow = 1;
        UserDynamicGuestNetImpl
                .query_new_update_dynamic_guest(token, userDynamicId, pageNow, pageSize,
                        token + "_query_new_update_dynamic_guest_" + userDynamicId + "_" + pageNow,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                bottomLoading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                bottomLoading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestDomain domain = gson.fromJson(response.body(), DynamicGuestDomain.class);
                                    if (domain.getData() != null &&
                                            domain.getData().getNewUpdateGuest() != null
                                            && domain.getData().getNewUpdateGuest().size() != 0) {
                                        noData.setVisibility(View.GONE);
                                        newUpdateTitle.setVisibility(View.VISIBLE);
                                        newUpdateAdpater.refreshList(domain.getData().getNewUpdateGuest());
                                    } else {
                                        newUpdateTitle.setVisibility(View.GONE);
                                        noData.setVisibility(View.VISIBLE);
                                    }
                                    if (domain.getData() != null &&
                                            domain.getData().getHotGuest() != null
                                            && domain.getData().getHotGuest().size() != 0) {
                                        hotTitle.setVisibility(View.VISIBLE);
                                        hotAdpater.refreshList(domain.getData().getHotGuest());
                                    } else {
                                        hotTitle.setVisibility(View.GONE);
                                    }

                                }
                            }

                            @Override
                            public void onCacheSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestDomain domain = gson.fromJson(response.body(), DynamicGuestDomain.class);
                                    if (domain.getData() != null &&
                                            domain.getData().getNewUpdateGuest() != null
                                            && domain.getData().getNewUpdateGuest().size() != 0) {
                                        noData.setVisibility(View.GONE);
                                        newUpdateTitle.setVisibility(View.VISIBLE);
                                        newUpdateAdpater.refreshList(domain.getData().getNewUpdateGuest());
                                    } else {
                                        newUpdateTitle.setVisibility(View.GONE);
                                        noData.setVisibility(View.VISIBLE);
                                    }
                                    if (domain.getData() != null &&
                                            domain.getData().getHotGuest() != null
                                            && domain.getData().getHotGuest().size() != 0) {
                                        hotTitle.setVisibility(View.VISIBLE);
                                        hotAdpater.refreshList(domain.getData().getHotGuest());
                                    } else {
                                        hotTitle.setVisibility(View.GONE);
                                    }

                                }
                            }
                        });

    }

    //分页最新动态评论,追加
    public void query_new_update_dynamic_guest_append(String token, Integer userDynamicId
    ) {

        pageNow++;
        UserDynamicGuestNetImpl
                .query_new_update_dynamic_guest(token, userDynamicId, pageNow, pageSize,
                        token + "_query_new_update_dynamic_guest_" + userDynamicId,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                isMoreLoading = true;
                                bottomLoading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                isMoreLoading = false;
                                bottomLoading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestDomain domain = gson.fromJson(response.body(), DynamicGuestDomain.class);
                                    if (domain.getData() != null &&
                                            domain.getData().getNewUpdateGuest() != null
                                            && domain.getData().getNewUpdateGuest().size() != 0) {
                                        newUpdateAdpater.appendList(domain.getData().getNewUpdateGuest());
                                    }
                                }
                            }


                        });

    }
    public void initData() {
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        String token = "";
        if (onlineUser == null) {
            token = "";
        } else {
            token = onlineUser.getToken();
        }
        query_new_update_dynamic_guest(token, id);
    }


    public void initGuestDialog() {
        Dialog guest_dialog;
        EditText guest_content_edit;
        guest_dialog = new Dialog(this, R.style.dialog_soft_input);
        guest_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        guest_dialog.setContentView(R.layout.dialog_dynamic_guest_input);
        WindowManager.LayoutParams lp = guest_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.BOTTOM;
        guest_dialog.getWindow().setAttributes(lp);

        guest_content_edit = guest_dialog.findViewById(R.id.content_edit);
        TextView guest_num_count = guest_dialog.findViewById(R.id.num_count);
        TextView guest_send_guest_bt = guest_dialog.findViewById(R.id.send_guest_bt);
        View exit_bt = guest_dialog.findViewById(R.id.exit_bt);
        exit_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                guest_dialog.dismiss();
            }
        });
        guest_dialog.findViewById(R.id.rootView)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        guest_dialog.dismiss();
                    }
                });
        guest_content_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                guest_num_count.setText(guest_content_edit.getText().length() + "/100");
                if (guest_content_edit.getText().length() == 0) {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                    guest_send_guest_bt.setClickable(false);
                } else {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_theme_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                    guest_send_guest_bt.setClickable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        guest_send_guest_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User onlineUser = UserService
                        .getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                    return;
                }
                send_dynamic_guest(onlineUser.getToken(),
                        id,
                        guest_content_edit.getText().toString().trim(), guest_dialog);

            }
        });
        guest_send_guest_bt.setClickable(false);
        guest_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //    guest_content_edit.getText().clear();
                // 显示软键盘
                guest_content_edit.requestFocus();
                SoftInputUtils.openSoftInput(DynamicDetailGuestListActivity.this, guest_dialog.getCurrentFocus(), 50);


                //  SoftInputUtils.showSoftInput(DynamicDetailActivity.this,guest_dialog);
            }
        });
        guest_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                SoftInputUtils.closedSoftInput(DynamicDetailGuestListActivity.this);
//                im.hideSoftInputFromWindow(guest_content_edit.getWindowToken(),0);
                guest_content_edit.getText().clear();
            }
        });
        guest_dialog.show();
    }

    //发送动态评论
    public void send_dynamic_guest(String token, Integer userDynamicId,
                                   String userDynamicGuestContent, Dialog dialog) {
        UserDynamicGuestNetImpl
                .send_dynamic_guest(token, userDynamicId, userDynamicGuestContent,
                        token + "_send_dynamic_guest_" + userDynamicId,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            dialog.dismiss();
                                            User onlineUser = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
                                            String token = "";
                                            if (onlineUser == null) {
                                                token = "";
                                            } else {
                                                token = onlineUser.getToken();
                                            }
                                            query_new_update_dynamic_guest(token, id);
//                                            Sneaker.with(DynamicDetailGuestListActivity.this)
//                                                    .autoHide(true)
//                                                    .setTitle("" + domain.getMessage(), R.color.white)
//                                                    .sneakSuccess();
                                            break;
                                        default:
//                                            Sneaker.with(DynamicDetailGuestListActivity.this)
//                                                    .autoHide(true)
//                                                    .setTitle("" + domain.getMessage(), R.color.white)
//                                                    .sneakError();
                                            showToast( domain.getMessage());
                                            break;
                                    }

                                }
                            }
                        });

    }

}
